package cn.sinjet.carassist;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import com.amap.navi.NaviModel;
/*import com.amap.navi.ViewMapActivity;
import com.amap.navi.PoiSearchActivity;
import com.baidu.android.voicedemo.ApiActivity;*/
//import com.baidu.speech.EventListener;
//import com.baidu.speech.EventManager;
//import com.baidu.speech.EventManagerFactory;
import com.mgroup.wazehelper.R;
import com.waze.sdk.WazeSDKManager;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Instrumentation;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.ContentObserver;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Messenger;
import android.os.Parcelable;
import android.provider.Settings;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Toast;
import cn.sinjet.communication.broadcast.SinjetBroadcastHandler;
import cn.sinjet.entity.AppInfo;
import cn.sinjet.model.carassist.AppModel;
import cn.sinjet.model.carsystem.CarModel;
import cn.sinjet.myview.DoorOpenWarningView;
import cn.sinjet.myview.HintAlertDlg;
import cn.sinjet.myview.MyShortcut;
import cn.sinjet.phone.ContactsActivity;
import cn.sinjet.utils.AppInfoUtil;
import cn.sinjet.viewmodel.IUpdateUI;
import cn.sinjet.viewmodel.OnMyDlgActionListener;
import cn.sinjet.viewmodel.PageDefine;
import cn.sinjet.viewmodel.ViewDefine;
import cn.sinjet.viewmodel.ViewModel;

public class MainActivity extends Activity implements OnClickListener,OnLongClickListener,IUpdateUI{
	private static final int MAX_APP_COUNT = 12;	
	private int CAR_APP_COUNT = 0;
	private ViewPager mViewPager = null;
    private PagerAdapter mPagerAdapter = null; 
    private ArrayList<View> mViews = null;
	private ViewGroup mViewRoot;
	SparseArray<MyShortcut>  mShortcuts = new SparseArray<MyShortcut>(); 
	
	RadioGroup mPageIndicator;
	SeekBar    mSeekBarLight;
	
//    MyTextView mMusicTitleView;
//    MyTextView mMusicArtistView;
	private View vWazeConnect;
    boolean mOldIsCarControlSupport = false;
//    private EventManager mWpEventManager;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		Log.d("ui", "main activity on Create");
		  try{
		        LayoutInflater inflater = LayoutInflater.from(this);
				mViewRoot = (ViewGroup)inflater.inflate(R.layout.activity_main,null);
		        if(mViewRoot == null) finish();
				setContentView(mViewRoot);
				initView();
				initViewPager();
	        }catch(Exception e){
	        	e.printStackTrace();
	        	finish();
	        }catch (OutOfMemoryError e) {
				// TODO: handle exception
	        	e.printStackTrace();
	        	finish();
			}
		  
		   SinjetApplication.getInstance().addActivity(this);
		   initGPS();
	}
	
	private void initView(){
		mPageIndicator = (RadioGroup)mViewRoot.findViewById(R.id.page_indicator_container);
        mPageIndicator.check(R.id.page_indicator1);
	}

//	boolean isFirstEnter = true;
	LocationManager mLocationManager;
	private void initGPS(){
		if(!CarModel.getInstance().isFirstEnter())
			return;
//		MainModel.getIns().setFirstEnter(false);
		mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		
        if (!mLocationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
        	  refreshGpsStatus(false);
        	  if(AppModel.getInstance().getSettings().bAutoOpenGps){
		            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		            dialog.setTitle(null);
		            dialog.setMessage("GPS isn't enabled，enable it now?");
		            dialog.setPositiveButton("now",
		                    new android.content.DialogInterface.OnClickListener() {
		                        @Override
		                        public void onClick(DialogInterface arg0, int arg1) {
		                            // 转到手机设置界面，用户设置GPS
		                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		                            startActivityForResult(intent, 0); // 设置完成后返回到原来的界面
		                        }
		                    });
		            dialog.setNeutralButton("later", new android.content.DialogInterface.OnClickListener() {
		                @Override
		                public void onClick(DialogInterface arg0, int arg1) {
		                    arg0.dismiss();
		                }
		            } );
		            dialog.show();
        	  }
        } else {
      	    refreshGpsStatus(true);
        }
	}

	 private final ContentObserver mGpsMonitor = new ContentObserver(null) {
	        @Override
	        public void onChange(boolean selfChange) {
	            super.onChange(selfChange);

	            boolean enabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//	            System.out.println("gps enabled? " + enabled);
	            refreshGpsStatus(enabled);
	        }
	    };
	    
	 private void refreshGpsStatus(boolean enabled){
		 final int COLOR_GREY = 0xFF888888;
		 final int COLOR_GREEN = 0xFF70F310;
		 if(enabled){
			    ViewModel.getIns().setViewProperty(R.id.home_gps_status_img, 1);
	      	    ViewModel.getIns().setViewProperty(R.id.home_gps_status_text, getResources().getString(R.string.enable));
	      	    ViewModel.getIns().setViewProperty(R.id.home_gps_status_text, COLOR_GREEN);
		 }else{
			  ViewModel.getIns().setViewProperty(R.id.home_gps_status_img, 0);
       	      ViewModel.getIns().setViewProperty(R.id.home_gps_status_text, getResources().getString(R.string.disable));
       	      ViewModel.getIns().setViewProperty(R.id.home_gps_status_text, COLOR_GREY);
		 }
	 }
	 
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		ViewModel.getIns().onActivityResume(this, PageDefine.PAGE_HOME, null);
		ViewModel.getIns().setUIListener(this);
		setUIViewProperty(mViewRoot);
		SinjetApplication.getInstance().showFloatMenu(false);
//		ViewModel.getIns().getUIMsgSaveCenter().restoreUIProperty(mMusicArtistView);
//		ViewModel.getIns().getUIMsgSaveCenter().restoreUIProperty(mMusicTitleView);
		if(mOldIsCarControlSupport != CarModel.getInstance().controlModule.isCarControlSupport())
		refreshApps();
//		MainModel.getIns().oldNaviModel.startLocation();
//		NaviModel.getInstance().startLocation();
		
		if(vWazeConnect != null)  ViewModel.getIns().getUIMsgSaveCenter().restoreUIProperty(vWazeConnect);
//		registerWakeupEvent();
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
        // 停止唤醒监听
//        mWpEventManager.send("wp.stop", null, null, 0, 0);
	}
	/*void registerWakeupEvent(){
		// 唤醒功能打开步骤
        // 1) 创建唤醒事件管理器
        mWpEventManager = EventManagerFactory.create(MainActivity.this, "wp");

        // 2) 注册唤醒事件监听器
        mWpEventManager.registerListener(new EventListener() {
            @Override
            public void onEvent(String name, String params, byte[] data, int offset, int length) {
                Log.d("voice", String.format("event: name=%s, params=%s", name, params));
                try {
                    JSONObject json = new JSONObject(params);
                    if ("wp.data".equals(name)) { // 每次唤醒成功, 将会回调name=wp.data的时间, 被激活的唤醒词在params的word字段
                        String word = json.getString("word");
                        onClkStartVoiceRecognizer();
//                        txtLog.append("唤醒成功, 唤醒词: " + word + "\r\n");
                    } else if ("wp.exit".equals(name)) {
//                        txtLog.append("唤醒已经停止: " + params + "\r\n");
                    }
                } catch (JSONException e) {
                    throw new AndroidRuntimeException(e);
                }
            }
        });

        // 3) 通知唤醒管理器, 启动唤醒功能
        HashMap params = new HashMap();
        params.put("kws-file", "assets:///WakeUp.bin"); // 设置唤醒资源, 唤醒资源请到 http://yuyin.baidu.com/wake#m4 来评估和导出
        mWpEventManager.send("wp.start", new JSONObject(params).toString(), null, 0, 0);
	}*/
	public void setUIViewProperty(ViewGroup vg) {
		for (int i = 0; i < vg.getChildCount(); i++) {
			View v = vg.getChildAt(i);
			if (v instanceof ViewGroup) {
				setUIViewProperty((ViewGroup) v);
			} else {
				ViewModel.getIns().getUIMsgSaveCenter().restoreUIProperty(v);
			}
		}
	}
	
	public View createView(int layout) {
		Log.d("ing", "onCreateView");
		LayoutInflater inflater = LayoutInflater.from(this);
		View v = inflater.inflate(layout, null);
		return v;
	}
	private void initViewPager() {
		// TODO Auto-generated method stub
		 View lay1 = createView(R.layout.page_main);
     	 View lay2 = createView(R.layout.page_apps_one);
     	 View lay3 = createView(R.layout.page_apps_two);
     	 if(lay1 == null || lay2 == null || lay3 == null) return;
     	 
     	 mViews = new ArrayList<View>();
    	 mViews.add(lay1);
    	 mViews.add(lay2);
    	 mViews.add(lay3);
    	 
    	  initPageMain(lay1); 
    	  initPageApps(lay2,lay3);
    	  for(int i=0;i<mShortcuts.size();i++){
    		  mShortcuts.valueAt(i).setOnClickListener(this);
    		  mShortcuts.valueAt(i).setOnLongClickListener(this);
    	  }
    	  
         mViewPager = (ViewPager) mViewRoot.findViewById(R.id.viewPager);
         mPagerAdapter = new MyPagerAdapter();
         mViewPager.setAdapter(mPagerAdapter);
         mViewPager.setOnPageChangeListener(mPageChangeListener);
         mViewPager.setCurrentItem(0);
         
	}
	
	private void  initPageApps(View pageView1,View pageView2){
		int[] pageIds1 = new int[]{R.id.shortcut1,R.id.shortcut2,R.id.shortcut3,R.id.shortcut4,R.id.shortcut5,R.id.shortcut6};
		int[] pageIds2 = new int[]{R.id.shortcut7,R.id.shortcut8,R.id.shortcut9,R.id.shortcut10,R.id.shortcut11,R.id.shortcut12};
		
		
		for(int id:pageIds1){
			MyShortcut shortcut = (MyShortcut)pageView1.findViewById(id);
			shortcut.setOnClickListener(this);
			shortcut.setOnLongClickListener(this);
			mShortcuts.put(id, shortcut);
		}
		for(int id:pageIds2){
			MyShortcut shortcut = (MyShortcut)pageView2.findViewById(id);
			shortcut.setOnClickListener(this);
			shortcut.setOnLongClickListener(this);
			mShortcuts.put(id, shortcut);
		}
		
		refreshApps();
	}
	
	
	private void refreshApps(){
		if(mShortcuts == null) return;
//		boolean isCarControlSupport = CarModel.getInstance().controlModule.isCarControlSupport();
//		mOldIsCarControlSupport = isCarControlSupport;
//		if(isCarControlSupport)
//			CAR_APP_COUNT = 4;
		if(mShortcuts.size() < CAR_APP_COUNT) return;
		
		/*MyShortcut baiduNavi = mShortcuts.valueAt(0);
		baiduNavi.setText("Baidu Navi");
		baiduNavi.setImageResource(R.drawable.ic_baidu_navi);
		baiduNavi.setFlag(MyShortcut.FLAG_CAR_APP);
		
		MyShortcut carCondiction = mShortcuts.valueAt(1);
		carCondiction.setText(getResources().getString(R.string.vehicle_detection));
		carCondiction.setImageResource(R.drawable.ic_car_condition);
		carCondiction.setFlag(MyShortcut.FLAG_CAR_APP);
		
		MyShortcut settings = mShortcuts.valueAt(2);
		settings.setText(getResources().getString(R.string.settings));
		settings.setImageResource(R.drawable.ic_settings);
		settings.setFlag(MyShortcut.FLAG_CAR_APP);
		
		if(CAR_APP_COUNT == 4){
			MyShortcut carControl = mShortcuts.valueAt(3);
			carControl.setText("蓝牙遥控");
			carControl.setImageResource(R.drawable.ic_car_control);
			carControl.setFlag(MyShortcut.FLAG_CAR_APP);
		}*/
		
		int addedAppSize = 0;
		List<AppInfo> appInfos = AppModel.getInstance().getAppInfos();
		for(int i=CAR_APP_COUNT;i<MAX_APP_COUNT;i++){
		    if(appInfos != null && (i-CAR_APP_COUNT<appInfos.size())){
		    	AppInfo appInfo = appInfos.get(i-CAR_APP_COUNT);
            	AppInfoUtil.setAppInfo(appInfo, this);
            	MyShortcut shortcut = mShortcuts.valueAt(i);
            	if(shortcut != null) {
            		shortcut.setAppInfo(appInfo);
            		shortcut.setFlag(MyShortcut.FLAG_THARD_APP);
            	}
		    }else{//
		    	MyShortcut shortcut = mShortcuts.valueAt(i);
		    	shortcut.setFlag(MyShortcut.FLAG_NONE);
		    }
         }
		if(appInfos != null)
		    addedAppSize = appInfos.size();
        if(CAR_APP_COUNT+addedAppSize < MAX_APP_COUNT){        
           MyShortcut add = mShortcuts.valueAt(CAR_APP_COUNT+addedAppSize);
           add.setFlag(MyShortcut.FLAG_ADD);
        }

        for(int i=0;i<MAX_APP_COUNT;i++){
        	MyShortcut shortcut = mShortcuts.valueAt(i);
        	shortcut.refresh();
        }
        AppModel.getInstance().storeAppData();
	}
	
	private void initPageMain(View v){
//		mMusicTitleView = (MyTextView)v.findViewById(R.id.home_music_title);
//		mMusicArtistView = (MyTextView)v.findViewById(R.id.home_music_artist);
		 View waze = v.findViewById(R.id.waze_map);
		 vWazeConnect = v.findViewById(R.id.waze_connect_state);
		 if(waze != null)
		 waze.setOnClickListener(this);
		 
	     MyShortcut  carMeterView = (MyShortcut)v.findViewById(R.id.home_car_meter);
	     carMeterView.setText(getResources().getString(R.string.car_meter));
	     carMeterView.setImageResource(R.drawable.ic_car_meter);
	     carMeterView.setFlag(MyShortcut.FLAG_CAR_APP);
	     carMeterView.refresh();
	     
	     MyShortcut  phoneView = (MyShortcut)v.findViewById(R.id.home_phone);
	     phoneView.setImageResource(R.drawable.ic_phone);
	     phoneView.setText(getResources().getString(R.string.dialer));
	     phoneView.setFlag(MyShortcut.FLAG_CAR_APP);
	     phoneView.refresh();
	     
	     MyShortcut  vehicleDectectView = (MyShortcut)v.findViewById(R.id.home_car_condition);
	     vehicleDectectView.setImageResource(R.drawable.ic_car_condition);
	     vehicleDectectView.setText(getResources().getString(R.string.vehicle_detection));
	     vehicleDectectView.setFlag(MyShortcut.FLAG_CAR_APP);
	     vehicleDectectView.refresh();
	     
	     MyShortcut  settingsView = (MyShortcut)v.findViewById(R.id.home_setting);
	     settingsView.setImageResource(R.drawable.ic_settings);
	     settingsView.setText(getResources().getString(R.string.settings));
	     settingsView.setFlag(MyShortcut.FLAG_CAR_APP);
	     settingsView.refresh();
//	     v.findViewById(R.id.home_gaode_navi).setOnClickListener(this);
//	     baiduView.setOnClickListener(this);
	     carMeterView.setOnClickListener(this);
//	     carConditionView.setOnClickListener(this);
	     phoneView.setOnClickListener(this);
	     vehicleDectectView.setOnClickListener(this);
	     settingsView.setOnClickListener(this);
	}
	
	
	
	private class MyPagerAdapter extends PagerAdapter{  
	  	  
        @Override  
        public void destroyItem(View v, int position, Object obj) {  
            // TODO Auto-generated method stub  
            ((ViewPager)v).removeView(mViews.get(position));  
        }  

        @Override  
        public void finishUpdate(View arg0) {  
            // TODO Auto-generated method stub  
              
        }  

        @Override  
        public int getCount() {  
            // TODO Auto-generated method stub  
            return mViews.size();  
        }  

        @Override  
        public Object instantiateItem(View v, int position) {  
            ((ViewPager)v).addView(mViews.get(position));  
            return mViews.get(position);  
        }  

        @Override  
        public boolean isViewFromObject(View arg0, Object arg1) {  
            // TODO Auto-generated method stub  
            return arg0 == arg1;  
        }  

        @Override  
        public void restoreState(Parcelable arg0, ClassLoader arg1) {  
            // TODO Auto-generated method stub  
              
        }  

        @Override  
        public Parcelable saveState() {  
            // TODO Auto-generated method stub  
            return null;  
        }  

        @Override  
        public void startUpdate(View arg0) {  
            // TODO Auto-generated method stub  
        }  
    }
	
	private OnPageChangeListener mPageChangeListener = new OnPageChangeListener() {

        @Override
        public void onPageSelected(int index)
        {
        	Log.d("ui", "onPageSelected :"+index);
//        	pageLifecircle(index);
        	switch(index){
        	case 0:
        		mPageIndicator.check(R.id.page_indicator1);
        		break;
        	case 1:
        		mPageIndicator.check(R.id.page_indicator2);
        		break;
        	case 2:
        		mPageIndicator.check(R.id.page_indicator3);
        		break;
        	}
        	
        }

		@Override
        public void onPageScrolled(int arg0, float arg1, int arg2)
        {

        }

        @Override
        public void onPageScrollStateChanged(int arg0)
        {

        }
    };
    
    OsdMenu menu = null;
//    FloatMenu floatMenu = null;
	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch(view.getId()){
//		case R.id.home_start_voice:
//			onClkStartVoiceRecognizer();
//			break;
		case R.id.home_music_playpause:
           onClkPlayPause();
		   break;
		case R.id.home_music_next:
			onClkNext();
			break;
		case R.id.home_phone:
			ViewModel.getIns().startActivity(ContactsActivity.class);
			break;
		case R.id.home_music_album:{
            Intent intent = new Intent("cn.sinjet.mediaplayer.LAUNCH");
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			SinjetApplication.getInstance().startActivity(intent);
		}break;
		case R.id.home_car_meter:
			ViewModel.getIns().jumpPageInUIThread(PageDefine.PAGE_CAR_METER);
			break;
		case R.id.home_car_condition:
			ViewModel.getIns().jumpPageInUIThread(PageDefine.PAGE_CAR_CONDITION);
			break;
		case R.id.home_setting:
			ViewModel.getIns().jumpPageInUIThread(PageDefine.PAGE_SETTING_GENERAL);
			break;
		case R.id.shortcut1:
		case R.id.shortcut2:
		case R.id.shortcut3:
		case R.id.shortcut4:
		case R.id.shortcut5:
		case R.id.shortcut6:
		case R.id.shortcut7:
		case R.id.shortcut8:
		case R.id.shortcut9:
		case R.id.shortcut10:
		case R.id.shortcut11:
		case R.id.shortcut12:
		       onClkShortCut(view);
		        break;
		case R.id.waze_map:
			startWazeMap();
			break;
		}
	}
	
	void startWazeMap(){
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 01, new Intent(this,MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
		WazeClient.getInstance().intClient(this, pendingIntent);
	}
	
	Messenger mRecvMessenger = new Messenger(new MessageHandler(MainActivity.this));
	
	class MessageHandler extends Handler{
		WeakReference <MainActivity> mActivity ;
		public MessageHandler(MainActivity activity) {
			// TODO Auto-generated constructor stub
			mActivity = new WeakReference <MainActivity>(activity);
		}
	}
	
	private void onClkStartVoiceRecognizer() {
	// TODO Auto-generated method stub
	/*	Intent intent = new Intent(this, ApiActivity.class);
		intent.putExtra("isNeedStart", 1);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	    startActivity(intent);*/
   }

	boolean mIsDeleteMode = false;
	private void enterDeleteShortcutMode() {
		 mIsDeleteMode = true;
		// TODO Auto-generated method stub
		  for(int i=0;i<mShortcuts.size();i++){
			  MyShortcut shortcut = mShortcuts.valueAt(i);
			  shortcut.setDeleteMode(true);
			  shortcut.refresh();
		  }
	}
	
	private void cancelDeleteModel(){
		mIsDeleteMode = false;
		for(int i=0;i<mShortcuts.size();i++){
			  MyShortcut shortcut = mShortcuts.valueAt(i);
			  shortcut.setDeleteMode(false);
			  shortcut.refresh();
		  }
	}
	
	void onClkShortCut(View view){
		  Log.d("view", "onClkShortcut"+view.getId());
		  MyShortcut shortcut = mShortcuts.get(view.getId(),null);
	      if(shortcut == null) return;
	      int flag = shortcut.getFlag();
	      switch(flag){
	      case MyShortcut.FLAG_NONE:
	    	  if(mIsDeleteMode) {
					cancelDeleteModel();
			  }
	    	  break;
	      case MyShortcut.FLAG_CAR_APP:
	    	  if(mIsDeleteMode) {
					cancelDeleteModel();
					return;
			  }
	    	  switch(view.getId()){
	    	  case R.id.shortcut1:
	    		  CarModel.getInstance().devModule.tryToConnectBaiduNavi();
//	    		  ViewModel.getIns().showDoorWarnView(0,1,1,0,0);
//	    		  ViewModel.getIns().startActivity(RadarActivity.class);
	    		  break;
	    	  case R.id.shortcut2:
	    		  ViewModel.getIns().jumpPageInUIThread(PageDefine.PAGE_CAR_CONDITION);
	    		  break;
	    	  case R.id.shortcut3:
	    		  ViewModel.getIns().jumpPageInUIThread(PageDefine.PAGE_SETTING_GENERAL);
	    		  break;
	    	  case R.id.shortcut4:
	    		  onClkCarControl();
	    	     break;
	    	  }
	    	    
	    	  break;
	      case MyShortcut.FLAG_ADD:
	    	  if(mIsDeleteMode) {
					cancelDeleteModel();
					return;
				}
	    	  Intent intent = new Intent(MainActivity.this,ChooseShortcutActivity.class);
		      intent.putExtra("ShortcutId", view.getId());
		      startActivityForResult(intent, 1);
	    	  break;
	      case MyShortcut.FLAG_THARD_APP:
	    	  Log.d("view", "onClkShortcut flag FLAG_THARD_APP "+view.getId());
	    	  if(shortcut.isDeleteMode()){
					 if(shortcut.getAppInfo() !=null){
						 List<AppInfo> appInfos = AppModel.getInstance().getAppInfos();
					     if(appInfos != null){
					    	 int index = mShortcuts.indexOfKey(view.getId())-CAR_APP_COUNT;
					    	 if(index >=0 && index < appInfos.size())
                                  appInfos.remove(index);
					         refreshApps();
					     }
					  }
					 else 
						 cancelDeleteModel();
				  return;
			 }
	    	  if(shortcut.getAppInfo() != null){
	    		  try{
						Intent appIntent = shortcut.getAppInfo().appIntent;
						Log.d("apps", "appIntent");
						SinjetApplication.getInstance().showFloatMenu(true);
			  	        startActivity(appIntent);
			  	  }catch(Exception e){
			  	        Toast.makeText(this, "launch app failed", Toast.LENGTH_LONG).show();
			  	  }
	    	  }
	    	  break;
	      }
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		// TODO Auto-generated method stub
//		super.onActivityResult(arg0, arg1, arg2);
		Log.d("navi","onActivity Request:"+requestCode+"result"+resultCode);
		if(resultCode == 0 && requestCode==1){
//			int shortcutId = intent.getIntExtra("ShortcutId", -1);
//			Log.d("navi", "onActivityResult shortcutId ="+shortcutId);
			refreshApps();
		}
	}

	@Override
	public boolean onLongClick(View view) {
		// TODO Auto-generated method stub
		switch(view.getId()){
		case R.id.shortcut1:
		case R.id.shortcut2:
		case R.id.shortcut3:
		case R.id.shortcut4:
		case R.id.shortcut5:
		case R.id.shortcut6:
		case R.id.shortcut7:
		case R.id.shortcut8:
		case R.id.shortcut9:
		case R.id.shortcut10:
		case R.id.shortcut11:
		case R.id.shortcut12:
			onLongClkShortcut(view);
			break;
	/*	case R.id.home_go_home:{
//			TTSController.getInstance(this).playText("设置家的地址");
			NaviModel.getInstance().playText("设置家的地址");
			 Intent naviIntent = new Intent(MainActivity.this,PoiSearchActivity.class);
			 naviIntent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
			 naviIntent.putExtra("requestCode", Utils.REQUEST_GO_HOME);
			 startActivity(naviIntent);
		}break;
		case R.id.home_go_office:{
//			TTSController.getInstance(this).playText("设置公司地址");
			NaviModel.getInstance().playText("设置公司地址");
			 Intent naviIntent = new Intent(MainActivity.this,PoiSearchActivity.class);
			 naviIntent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
			 naviIntent.putExtra("requestCode", Utils.REQUEST_TO_OFFICE);
			 startActivity(naviIntent);
		   }break;*/
		}
		return true;
	}

    void onLongClkShortcut(View view){
    	if(mShortcuts.get(view.getId(),null) !=null) 
			enterDeleteShortcutMode();
    }
	
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			checkExit();
		}
		return true;
	}
	
	private long exitTime;
	void checkExit() {
 		if ((System.currentTimeMillis() - exitTime) > 2000) {
 			Toast.makeText(getApplicationContext(), "press again to exit",
 					Toast.LENGTH_SHORT).show();
 			exitTime = System.currentTimeMillis();
 		} else {
 			    SinjetApplication.getInstance().exit();
 		}
 	}

	@Override
	public void resetContentView(int layout) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void finishActivity() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void updateUI(Bundle data) {
		// TODO Auto-generated method stub
		int viewId = data.getInt("id");
//		Log.d("ui", "sinjet ui update ui:"+viewId);
		if(viewId == -1) return;
		switch(viewId){
		case R.id.viewPager:
			break;
		/*case R.id.home_music_artist:
			ViewModel.getIns().getUIMsgSaveCenter().restoreUIProperty(mMusicArtistView);
			break;
		case R.id.home_music_title:
			ViewModel.getIns().getUIMsgSaveCenter().restoreUIProperty(mMusicTitleView);
			break;*/
		case R.layout.layout_password_dialog:
			showPasswordPannel();
			break;
		case ViewDefine.VIEW_APPS_LIST:
			refreshApps();
			break;
//		case R.id.waze_connect_state:
//			if(vWazeConnect != null)
//			ViewModel.getIns().getUIMsgSaveCenter().restoreUIProperty(vWazeConnect);
//			break;
		}	
		View v = mViewRoot.findViewById(viewId);
		if(v != null)  ViewModel.getIns().getUIMsgSaveCenter().restoreUIProperty(v);
		
	}
	
	
	PasswordPannel  pp = null;
	   void showPasswordPannel(){
		   if(pp == null)
			   pp = new PasswordPannel(this, R.style.CustomDialog);
		   pp.show();
	   }
	
	
	private void goFirstPage(){
		if(mViewPager.getCurrentItem() != 0)
		mViewPager.setCurrentItem(0);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.d("ui", "main activity onDestroy");
	}
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		getContentResolver().registerContentObserver(
                Settings.Secure.getUriFor(Settings.System.LOCATION_PROVIDERS_ALLOWED),false, mGpsMonitor);
	}
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		getContentResolver().unregisterContentObserver(mGpsMonitor);
	}
	
	
	private void emulateMediaButton(final int keyCode){
		 new Thread(){
				public void run(){
					try{
						Instrumentation inst = new Instrumentation();
						inst.sendKeyDownUpSync(keyCode);
					} catch (Exception e){
						e.printStackTrace();
					}
				}
			 }.start();
	 }
	
	void onClkPlayPause(){
		if(SinjetApplication.getInstance().isMediaFocuseOn()){
			SinjetBroadcastHandler.requestPlayPause(this);
		}else{
			emulateMediaButton(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
		}
	}
	void onClkNext(){
		if(SinjetApplication.getInstance().isMediaFocuseOn()){
			SinjetBroadcastHandler.requestPlayNext(this);
		}else{
			emulateMediaButton(KeyEvent.KEYCODE_MEDIA_NEXT);
		}
	}
	
   void onClkCarControl(){
	   CarModel.getInstance().controlModule.onClkCarControl();   
   }

	@Override
	public void showAlertDialog(String positive,String nagative, String content, final OnMyDlgActionListener actionListener) {
		// TODO Auto-generated method stub
		HintAlertDlg pswAlertDlg = new HintAlertDlg(this);
		pswAlertDlg.setButtonText(positive, nagative);
		pswAlertDlg.show(content, actionListener);
	}
	
	DoorOpenWarningView mDoorOpenWarningView = null;
	@Override
	public void showDoorWarn(int[] doors) {
		// TODO Auto-generated method stub
		if(doors == null || doors.length !=5) return;
		if(mDoorOpenWarningView == null)
			mDoorOpenWarningView = new DoorOpenWarningView(this,R.style.CustomDialog);
		if(mDoorOpenWarningView != null){
			mDoorOpenWarningView.showOsdView(doors[0],doors[1],doors[2],doors[3],doors[4]);
		}
	}
}
